package com.ssh.dao.impl;

import com.ssh.dao.IBaseDao;
import com.ssh.service.IBaseService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by liaoh on 2017/5/5.
 */
@Repository
public class IBaseDaoImpl<T, Pk extends Serializable> implements IBaseDao<T, Pk> {
    private Class<T> entityClass;
    protected SessionFactory sessionFactory;

    public IBaseDaoImpl() {
        this.entityClass = null;
        Class<?> c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizeType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizeType[0];
        }
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public T get(Pk id) {
        Assert.assertNotNull("id is required", id);
        return (T) getSession().get(entityClass, id);
    }

    public Pk save(T entity) {
        Assert.assertNotNull("entity is required", entity);
        return (Pk) getSession().save(entity);
    }
}
